package user

import (
	"context"
	"encoding/json"
	"enjoy-shop/formdata"
	"fmt"
	"gitee.com/enjoy_5/user-rpc/client"
	"gitee.com/enjoy_5/user-rpc/proto/user"
	"gitee.com/xuxinzhi2206/corehub/database/redis"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"gopkg.in/yaml.v2"
	"math/rand"
	"strconv"
	"time"
)

type CodeData struct {
	Code int `json:"code"`
}

type Sendsms struct {
	KeyId        string `yaml:"key_id"`
	KeySecret    string `yaml:"key_secret"`
	SignName     string `yaml:"sign_name"`
	TemplateCode string `yaml:"template_code"`
}

type Cofig struct {
	Sendsms Sendsms `yaml:"sendsms"`
}

// 用户登录
func Find(req *formdata.Login) (*user.UserFirstResponse, error) {
	info, err := client.UserFind(context.Background(), &user.UserFirstRequest{
		Phone: req.Phone,
	})
	if err != nil {
		return nil, err
	}
	return info, nil

}

// 发送验证码
func SendCode(req *formdata.SendCode) (string, error) {
	rand.Seed(time.Now().UnixNano())
	// 生成 1000 到 9999 之间的随机整数
	code := rand.Intn(8999) + 1000
	// 创建结构体实例
	res := CodeData{Code: code}
	// 将结构体转换为JSON字节切片
	jsonData, err := json.Marshal(res)
	if err != nil {
		return "", err
	}
	var s Cofig
	initNacos, err := nacos.GetConfig()
	err = yaml.Unmarshal([]byte(initNacos), &s)
	if err != nil {
		return "", err
	}
	keyId := s.Sendsms.KeyId
	keySecret := s.Sendsms.KeySecret
	signName := s.Sendsms.SignName
	templateCode := s.Sendsms.TemplateCode
	_, err = SendSms(req.Phone, string(jsonData), keyId, keySecret, signName, templateCode)
	if err != nil {
		return "", err
	}
	err = redis.SetRedis(req.Phone+req.Type+"minute", strconv.Itoa(code), 1*time.Minute)
	err = redis.SetRedis(req.Phone+req.Type, strconv.Itoa(code), 10*time.Minute)
	if err != nil {
		return "", err
	}
	fmt.Println("验证码", code)
	return strconv.Itoa(code), nil
}

// 用户注册
func UserSave(req *formdata.UserRegister) (*user.SaveUserResponse, error) {
	Info := user.SaveInfo{
		Phone:    req.Phone,
		Img:      ProfilePicture(),
		Pwd:      req.Pwd,
		UserName: GenerateNickname(),
	}
	_, err := client.UserSave(context.Background(), &user.SaveUserRequest{UserData: &Info})
	fmt.Println(44444444)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// 用户修改
func UserUpdate(req formdata.UserUpdate) (*user.UpdUserResponse, error) {
	Info := user.UserInfo{
		Id:       strconv.Itoa(req.Id),
		UserName: req.UserName,
		Phone:    req.Phone,
		Img:      req.Img,
		Pwd:      req.Pwd,
		Status:   int64(req.Status),
		Birthday: int64(req.Birthday),
		Sex:      int64(req.Sex),
	}
	_, err := client.UserUpdate(context.Background(), &user.UpdUserRequest{UserData: &Info})
	if err != nil {
		return nil, err
	}
	return nil, nil
}
